package com.zxc.item.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zxc.common.enums.ShoppingEnum;
import com.zxc.common.exception.ShoppingException;
import com.zxc.common.vo.ResultVo;
import com.zxc.item.dao.TbSkuMapper;
import com.zxc.item.entity.TbSku;
import com.zxc.item.service.TbSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class TbSkuServiceImpl implements TbSkuService {

    @Autowired
    private TbSkuMapper tbSkuMapper;

    @Override
    public ResultVo<TbSku> getList(int page,int limit) {
        //进行分页查询
        PageHelper.startPage(page,limit);

        //得到查询结果
        PageInfo<TbSku> pageInfo = new PageInfo<>(tbSkuMapper.selectAll());

        //判断是否有数据
        if (pageInfo.getList().isEmpty()){
            throw new ShoppingException(ShoppingEnum.SKU_LIST_NOT_FOUND);
        }

        ResultVo<TbSku> tbSkuResultVo = new ResultVo<>();
        tbSkuResultVo.setCount(Math.toIntExact(pageInfo.getTotal()));
        tbSkuResultVo.setData(pageInfo.getList());
        tbSkuResultVo.setPageNum(page);
        tbSkuResultVo.setMaxPage(pageInfo.getPages());

        return tbSkuResultVo;
    }

    @Override
    @Transactional
    public void  delSku(long id) {
        int result = tbSkuMapper.deleteByPrimaryKey(id);
        if (result <= 0){
            throw new ShoppingException(ShoppingEnum.DELETE_SKU_FAIL);
        }
    }

    @Override
    @Transactional
    public void saveSku(TbSku tbSku) {
        //指定上架时间
        tbSku.setCreateTime(new Date());

        //指定修改时间
        tbSku.setLastUpdateTime(new Date());
        int result = tbSkuMapper.insertSelective(tbSku);

        if (result <= 0){
            throw new ShoppingException(ShoppingEnum.SAVE_SKU_FAIL);
        }
    }

    //修改商品信息
    @Override
    @Transactional
    public void updateSku(TbSku tbSku) {
        tbSku.setLastUpdateTime(new Date());
        int result = tbSkuMapper.updateByPrimaryKeySelective(tbSku);
        if (result <= 0){
            throw new ShoppingException(ShoppingEnum.UPDATE_SKU_FAIL);
        }
    }
}
